//
// Created by user on 2022/1/19.
//
#include <vector>

using namespace std;
vector<int> spiralOrder(vector<vector<int>>& matrix) {
    int m = matrix.size();
    int n = matrix[0].size();

    int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int row =0;
    int col = 0;
    int di = 0;

    vector<int> res;
    vector<vector<bool>> seen(m, vector<bool>(n));
    for (int i = 0; i < n*m; ++i) {
        res.push_back(matrix[row][col]);
        seen[row][col] = true;
        int nextrow = row+dirs[di][0];
        int nextcol = col+dirs[di][1];

        if(nextrow>=m || nextrow<0 ||
        nextcol>=n || nextcol<0 ||seen[nextrow][nextcol]){
            di = (di+1)%4;
        }
        row =  row+dirs[di][0];
        col =  col+dirs[di][1];
    }

    return res;
}

